<template>
  <div class="rankings-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>动漫排行榜</h1>
      <p>月度社区投票决定的动漫排行榜</p>
    </div>
  
    
    <!-- 排行榜列表 -->
    <div class="rankings-list">
      <RankingAnimeModule
        :animes="displayedAnimes"
        :loading="loading"
        :loading-more="loadingMore"
        :has-more-data="hasMoreData"
        @vote="handleVote"
        @show-detail="showAnimeDetail"
      />
    </div>

    <!-- 动漫详情弹窗 -->
    <AnimeDetailModal
      v-if="selectedAnime"
      :anime="selectedAnime"
      @close="selectedAnime = null"
    />

    <!-- 登录提示弹窗 -->
    <LoginPromptModal/>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import RankingAnimeModule from '../components/RankingAnimeModule.vue'
import AnimeDetailModal from '../components/AnimeDetailModal.vue'
import LoginPromptModal from '../components/LoginPromptModal.vue'
import type { Anime } from '../types/anime'
import { getMonthlyRanking } from '../services/animeService'
import { batchCheckFavorites } from '../services/favoriteService'
import { isAuthenticated } from '../services/userService'
import { API_BASE_URL, API_PATHS } from '../services/apiConfig'
import { voteForAnime } from '../services/voteService'
import toastService from '../services/toastService'

// 页面状态
const loading = ref(false)
const loadingMore = ref(false)
const allAnimes = ref<Anime[]>([])
const displayedAnimes = ref<Anime[]>([])
const hasMoreData = ref(true)
const selectedAnime = ref<Anime | null>(null)
const currentPage = ref(1)
const pageSize = 15

// 显示动漫详情
const showAnimeDetail = (anime: Anime) => {
  selectedAnime.value = anime
}

// 模拟数据源已注释掉
// const mockAnimes: Anime[] = [
//   {
//     id: 1,
//     title: '鬼灭之刃 无限列车篇',
//     coverUrl: 'https://ts1.tc.mm.bing.net/th/id/OIP-C.0FQSOvu3OYJFe-h_sZKA6wHaNK?w=160&h=211&c=8&rs=1&qlt=90&o=6&cb=12&dpr=1.3&pid=3.1&rm=2',
//     releaseDate: '2020-10-16',
//     rating: 9.5,
//     votes: 12536,
//     favorites: 8900,
//     year: 2020,
//     season: '秋季',
//     genre: ['战斗', '热血', '奇幻'],
//     description: '灶门炭治郎和炼狱杏寿郎前往无限列车调查失踪事件，与下弦之壹魇梦展开激战。'
//   },
//   // 其他模拟数据项已省略
// ]

// sortedAnimes removed as it's not being used



// 批量更新收藏状态
const updateAnimeFavoritesStatus = async (animesToUpdate: Anime[]) => {
  try {
    if (isAuthenticated() && animesToUpdate.length > 0) {
      const animeIds = animesToUpdate.map(anime => anime.id)
      const favoritesMap = await batchCheckFavorites(animeIds)
      
      // 更新收藏状态 - favoritesMap是Record类型，使用方括号访问
      animesToUpdate.forEach(anime => {
        anime.isFavorite = favoritesMap[anime.id] || false
      })
    }
  } catch (error) {
    console.error('批量检查收藏状态失败:', error)
  }
}

  // 加载动漫数据
const loadAnimes = async () => {
  if (loading.value || loadingMore.value || !hasMoreData.value) return
  
  const isFirstLoad = displayedAnimes.value.length === 0
  if (isFirstLoad) {
    loading.value = true
    currentPage.value = 1
  } else {
    loadingMore.value = true
    currentPage.value++
  }
  
  try {
    // 调用API获取真实数据，传递分页参数
    const response = await getMonthlyRanking(currentPage.value, pageSize)
    
    // 获取records数组（后端返回的排行榜数据）
    const data = response.records || []
    
    // 将API返回的数据转换为Anime类型，适配新的数据格式
    const newAnimes = data.map((item: any) => {
      // 提取anime对象
      const animeData = item.anime || item;
      
      // 处理图片URL，通过代理服务加载
      let coverImageUrl = animeData.coverImageUrl;
      const defaultImageUrl = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.0FQSOvu3OYJFe-h_sZKA6wHaNK?w=160&h=211&c=8&rs=1&qlt=90&o=6&cb=12&dpr=1.3&pid=3.1&rm=2';
      
      // 如果有图片URL且包含http，通过代理服务加载
      if (coverImageUrl && coverImageUrl.includes('http')) {
        coverImageUrl = `${API_BASE_URL}${API_PATHS.DOUBAN.IMAGE_PROXY}?url=${encodeURIComponent(coverImageUrl)}`;
      } else if (defaultImageUrl) {
        // 默认图片也通过代理服务加载
        coverImageUrl = `${API_BASE_URL}${API_PATHS.DOUBAN.IMAGE_PROXY}?url=${encodeURIComponent(defaultImageUrl)}`;
      }
      
      return {
        id: animeData.id || 0,
        title: animeData.title || '',
        coverImageUrl,
        releaseDate: animeData.releaseDate || animeData.createdAt || new Date().toISOString().split('T')[0],
        rating: animeData.rating || 0,
        votes: item.voteCount || animeData.votes || 0, // 从外层或内层获取投票数
        favorites: animeData.favorites || 0,
        year: animeData.year || (animeData.createdAt ? new Date(animeData.createdAt).getFullYear() : 2024),
        season: animeData.season || 'FALL',
        genre: animeData.genre || '',
        description: animeData.description || animeData.synopsis || '',
        // 确保所有必要字段都被处理
        director: animeData.director || '',
        studio: animeData.studio || '',
        episodes: animeData.episodes || 0,
        tags: animeData.tags || '',
        doubanId: animeData.doubanId || '',
        createdAt: animeData.createdAt || new Date().toISOString(),
        // 确保type字段存在，如果没有则使用genre字段或默认值
        type: animeData.type || animeData.genre || '动画'
      }
    })
    
    // 根据是否是第一次加载来决定是替换还是追加数据
    if (isFirstLoad) {
      allAnimes.value = newAnimes
      displayedAnimes.value = newAnimes
    } else {
      allAnimes.value = [...allAnimes.value, ...newAnimes]
      displayedAnimes.value = [...displayedAnimes.value, ...newAnimes]
    }
    
    // 批量检查收藏状态
    await updateAnimeFavoritesStatus(newAnimes)
    
    // 判断是否还有更多数据
    hasMoreData.value = newAnimes.length === pageSize
  } catch (error) {
    console.error('加载动漫数据失败:', error)
    // 不使用模拟数据作为后备
    if (isFirstLoad) {
      allAnimes.value = []
      displayedAnimes.value = []
    }
    hasMoreData.value = false
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 处理投票
const handleVote = async (eventData: number | { animeId: number }) => {
  try {
    // 提取动漫ID
    const animeId = typeof eventData === 'object' ? eventData.animeId : eventData
    
    // 调用投票API
    await voteForAnime(animeId)
    
    // 保存当前滚动位置
    const currentScrollPosition = window.scrollY
    
    // 重置数据状态
    displayedAnimes.value = []
    allAnimes.value = []
    currentPage.value = 1
    hasMoreData.value = true
    
    // 重新加载数据
    await loadAnimes()
    
    // 恢复滚动位置
    setTimeout(() => {
      window.scrollTo({ top: currentScrollPosition, behavior: 'auto' })
    }, 100)
  } catch (error) {
    console.error('投票失败:', error)
    toastService.error('投票失败，请重试')
  }
}

// 由于我们已经修改了AnimeCard组件，移除了其中的voteForAnime调用
// 现在投票流程只在父组件中执行一次，避免了重复调用接口的问题

// 滚动加载更多
const handleScroll = () => {
  if (loading.value || loadingMore.value || !hasMoreData.value) return
  
  const scrollPosition = window.scrollY + window.innerHeight
  const documentHeight = document.documentElement.scrollHeight
  
  // 当滚动到距离底部100px时加载更多
  if (scrollPosition >= documentHeight - 100) {
    loadAnimes()
  }
}

// 组件挂载时加载数据并添加滚动监听
onMounted(async () => {
  // 加载动漫数据
  await loadAnimes()
  
  // 添加滚动事件监听
  window.addEventListener('scroll', handleScroll)
})

// 组件卸载时移除滚动监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
.rankings-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
  color: #FF69B4;
  text-shadow: 1px 1px 2px rgba(255, 105, 180, 0.3);
}

.page-header p {
  font-size: 1.1rem;
  color: #666;
}

.filter-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 30px;
  justify-content: center;
}

.filter-group,
.sort-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label,
.sort-group label {
  font-weight: 500;
  color: #333;
}

.filter-group select,
.sort-group select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
  font-size: 14px;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.filter-group select:focus,
.sort-group select:focus {
  outline: none;
  border-color: #FF69B4;
}

.loading,
.no-results {
  text-align: center;
  padding: 50px 20px;
  color: #666;
}

.ranking-item {
  margin-bottom: 20px;
  border-radius: 10px;
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.ranking-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

/* 排名数字样式 */
.rank-item {
  display: flex;
  align-items: stretch;
  gap: 15px;
}

.rank-number {
  min-width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  font-weight: bold;
  color: white;
  flex-shrink: 0;
  margin-top: 10px;
}

.rank-number.rank-1 {
  background-color: #FF69B4;
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.3);
}

.rank-number.rank-2 {
  background-color: #FF85A2;
  box-shadow: 0 4px 10px rgba(255, 133, 162, 0.25);
}

.rank-number.rank-3 {
  background-color: #FFA5B8;
  box-shadow: 0 4px 8px rgba(255, 165, 184, 0.2);
}

.regular-rank {
  background-color: #CCCCCC;
  font-size: 1.5rem;
  min-width: 50px;
  height: 50px;
}

/* 前三名特殊样式 - 粉色递减渐变背景 */
.ranking-item.rank-1 {
  background: linear-gradient(135deg, rgba(255,105,180,0.2) 0%, rgba(255,105,180,0.1) 100%);
  padding: 20px;
  border: 2px solid rgba(255,105,180,0.4);
}

.ranking-item.rank-2 {
  background: linear-gradient(135deg, rgba(255,105,180,0.15) 0%, rgba(255,105,180,0.08) 100%);
  padding: 18px;
  border: 1px solid rgba(255,105,180,0.3);
}

.ranking-item.rank-3 {
  background: linear-gradient(135deg, rgba(255,105,180,0.1) 0%, rgba(255,105,180,0.05) 100%);
  padding: 16px;
  border: 1px solid rgba(255,105,180,0.2);
}

/* 第四名及以后的统一样式 */
.ranking-item.regular-item {
  background: #f9f9f9;
  padding: 15px;
  border: 1px solid #eee;
}

.loading-more {
  padding: 20px;
  text-align: center;
}

.skeleton {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
  border-radius: 8px;
}

.no-more-data {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
}

/* 动画 */
@keyframes skeleton-loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-group,
  .sort-group {
    justify-content: space-between;
  }
  
  .page-header h1 {
    font-size: 2rem;
  }
  
  /* 排名数字响应式样式 */
  .rank-number {
    min-width: 45px;
    height: 45px;
    font-size: 1.5rem;
  }
  
  .rank-number.rank-1 {
    background-color: #FF69B4;
    box-shadow: 0 3px 9px rgba(255, 105, 180, 0.3);
  }
  
  .rank-number.rank-2 {
    background-color: #FF85A2;
    box-shadow: 0 3px 7px rgba(255, 133, 162, 0.25);
  }
  
  .rank-number.rank-3 {
    background-color: #FFA5B8;
    box-shadow: 0 3px 6px rgba(255, 165, 184, 0.2);
  }
  
  .regular-rank {
    font-size: 1.2rem;
    min-width: 40px;
    height: 40px;
  }
  
  /* 排名项目响应式样式 */
  .ranking-item {
    margin-bottom: 15px;
  }
  
  .ranking-item.rank-1 {
    padding: 15px;
  }
  
  .ranking-item.rank-2 {
    padding: 13px;
  }
  
  .ranking-item.rank-3 {
    padding: 11px;
  }
  
  .ranking-item.regular-item {
    padding: 10px;
  }
}

/* 小屏幕额外适配 */
@media (max-width: 480px) {
  .rank-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .rank-number {
    min-width: 40px;
    height: 40px;
    font-size: 1.3rem;
    margin-top: 0;
  }
  
  .rank-number.rank-1 {
    background-color: #FF69B4;
    box-shadow: 0 2px 6px rgba(255, 105, 180, 0.3);
  }
  
  .rank-number.rank-2 {
    background-color: #FF85A2;
    box-shadow: 0 2px 5px rgba(255, 133, 162, 0.25);
  }
  
  .rank-number.rank-3 {
    background-color: #FFA5B8;
    box-shadow: 0 2px 4px rgba(255, 165, 184, 0.2);
  }
  
  .regular-rank {
    font-size: 1.1rem;
    min-width: 35px;
    height: 35px;
  }
  
  /* 前三名特殊样式 - 小屏幕适配 */
  .ranking-item.rank-1 {
    padding: 12px;
    border-width: 1.5px;
  }
  
  .ranking-item.rank-2 {
    padding: 11px;
    border-width: 1.2px;
  }
  
  .ranking-item.rank-3 {
    padding: 10px;
    border-width: 1px;
  }
  
  .ranking-item.regular-item {
    padding: 8px;
  }
}
</style>